/**
 * 
 *     Code contributed by IUP Research Institute
 *
 * 
 *     This file is part of NetworkMon.
 *
 *   NetworkMon is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; version 2 of the License.
 *
 *   NetworkMon is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with NetworkMon; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
package networkgui;

/**
 * 
 * @author Brian Slocum
 */

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.Timer;

import networkbackend.packetQueue;

public class MasterForm extends javax.swing.JFrame {

	private static final int PORT_FTP = 21;
	private static final int PORT_WWW = 80;
	protected javax.swing.event.EventListenerList listenerList = new javax.swing.event.EventListenerList();

	private JScrollPane computerScrollPanel = new JScrollPane();
	private JScrollPane infoScrollPanel = new JScrollPane();
	private JPanel computerPanel = new JPanel();
	private JPanel infoPanel = new JPanel();
	private packetQueue theQ = new packetQueue("10.10.1.*");
//	private String currentComputerNode;
	private JSplitPane mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

	private JMenuBar menuMaster = new JMenuBar();
	private JMenu menuFile = new JMenu("File");
	private JMenu menuDevices = new JMenu("Devices");
	private JMenu menuControl = new JMenu("Control");
	private JMenuItem exitMenuItem = new JMenuItem("Exit");
	private JMenuItem startApplication = new JMenuItem("DO IT!");
	private JMenuItem stopApplication = new JMenuItem("STOP IT!");
	private JMenuItem logstream = new JMenuItem("Log Traffic");

	private JPopupMenu popupMaster = new JPopupMenu();
	private JMenuItem popupRefresh = new JMenuItem("Refresh");

	private JMenuItem emailMenuItem = new JMenuItem("Send Email");

	private ComputerNode theComputers = new ComputerNode();
	private ComputerInformation theComputerInfo = new ComputerInformation();

	private Timer masterTimer;
	private Boolean isTimerDone = false;
	private int currentComputerID = -1;

	/** Creates a new instance of Main */
	public MasterForm() {
		// init all controls
		initControls();
		this.setTitle("Network Monitor What Rocks!!!");

		// set up the timer and go damnit
		// remember the time is based in milliseconds
		masterTimer = new Timer(1000, new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				if (isTimerDone) {
					masterTimer.stop();
				} else {
					RefreshTheComputerListTable();
					RefreshTheComputerInformationTable();
				}
			}
		});

		// start the timer
		masterTimer.start();
	}

	private void initControls() {

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(700, 500);
		setLocation(200, 200);

		// set up the Main menu
		menuMaster.add(menuFile);
		menuMaster.add(menuDevices);
		menuMaster.add(menuControl);

		// set up the file menu
		menuFile.add(emailMenuItem);
		menuFile.add(exitMenuItem);

		// add the handler for the click event for the exit button
		emailMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// Bring up the email form here
				EmailForm newEmailForm;
				newEmailForm = new EmailForm();
				newEmailForm.setVisible(true);
			}
		});

		// add the handler for the click event for the exit button
		exitMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// exit the program 
				System.exit(0);
			}
		});

		// set up the Control menu
		menuControl.add(startApplication);
		menuControl.add(stopApplication);
		menuControl.add(logstream);
		// add the events for the controller

		startApplication.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// start capturing packets
				if (theQ.selectedDevice == -1) {
					JOptionPane.showMessageDialog(null,
							"Please Select a Network Device Before Starting");
				} else {
					theQ.start();
				}
			}
		});

		stopApplication.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// STOP!!!!!!
				theQ.stopIt();
			}
		});

		logstream.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// Write to the file
				// networkbackend.NetworkMon_Logger.LogIt("Eat Poo because it
				// can contain corn and other nuts.");
			}
		});

		// Set up the devices menu
		int count = 0;
		String[] tempDev = theQ.Devices();

		while (count < tempDev.length) {
			JRadioButtonMenuItem tempItem = new JRadioButtonMenuItem(
					tempDev[count]);

			// add handlers
			tempItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// set the selected device to the currently selected one
					// find the Devices Index by serching threw them all
					// I am sure we could do this a better way...
					String[] allDev = theQ.Devices();
					int count = 0;
					while (count < allDev.length) {
						if (allDev[count] == e.getActionCommand()) {
							theQ.selectedDevice = count;
							break;
						}
						count += 1;
					}
				}
			});

			// add to the menu
			menuDevices.add(tempItem);
			count += 1;
		}

		// Set up the Popup Menu
		popupMaster.add(popupRefresh);

		// add the refresh button listner
		popupRefresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// RefreshBox(currentComputerNode); //this is thread save
				// because Swing called it (duhh me)
			}
		});

		// set the borders
		computerPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
		infoPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

		// set up the Layout Managers
		computerPanel.setLayout(new BoxLayout(computerPanel, BoxLayout.Y_AXIS));
		computerScrollPanel.setViewportView(computerPanel);

		infoPanel.setLayout(new BorderLayout());

		// set up the popups
		infoPanel.setComponentPopupMenu(popupMaster);
		infoScrollPanel.setComponentPopupMenu(popupMaster);

		// set the Divider
		mainPanel.setDividerLocation(250);
		// add the controls to the panels
		computerPanel.add(theComputers);
		infoPanel.add(theComputerInfo);

		// add the listner for the user asking to see more information about the
		// computer
		theComputers.addListener(new ANodeWasClickedEvent() {
			public void ANodeWasClickedEvent(int e) {
				// stop the timer
				masterTimer.stop();
				// clear the computer information
				infoPanel.removeAll();

				// set the current ID
				currentComputerID = e;
				RefreshTheComputerInformationTable();

				masterTimer.start();
			}

		});

		// add the panels to the scroll panels
		computerScrollPanel.getViewport().add(computerPanel);
		infoScrollPanel.getViewport().add(infoPanel);

		// set the main panel up
		mainPanel.setLeftComponent(computerScrollPanel);
		mainPanel.setRightComponent(infoScrollPanel);

		// add the main panel to the main form
		add(mainPanel);

		// add the menu to the form
		setJMenuBar(menuMaster);

	}

	private void RefreshTheComputerListTable() {
		theComputers.updateComputerList(theQ.GetAddresses());

	}

	private void RefreshTheComputerInformationTable() {
		if (currentComputerID >= 0) {

			theComputerInfo = new ComputerInformation();
			theComputerInfo.setPacketInformation(((theQ
					.get(currentComputerID))).GetListPackets());
			infoPanel.add(theComputerInfo);
			infoPanel.validate();
		}
	}

	// the start of the main program
	public static void main(String[] args) {
		// thus this program begins
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new MasterForm().setVisible(true);
			}
		});
	}
}
